<?php
/*
 * @Author: 李明
 * @Date: 2021-11-30 18:32:01
 * @LastEditTime: 2022-01-07 20:03:09
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/app/data/PieChartController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\app\data;

use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Utils;
use App\Models\Branch;
use App\Models\FamiliesMoneyRecord;
use App\Models\InterestRecord;
use App\Models\Worker;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PieChartController extends Controller
{

    /**
     * @description: 年化/规模 双 饼状图
     * @param {Request} $request
     * @return {*}
     */
    public function pieDataResultsList(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $worker_id = $tokenInfo['worker_id'];
            $worker = Worker::find($worker_id);
            $start_time = $all['start_time'];
            $end_time = $all['end_time'];
            $is_first = $all['is_first'] ?? 0;
            $branch_id = $all['branch_id'] ?? ($worker->branchesManage->first()->id ?? '');
            if ($branch_id == '') { // 则没有权限
                return LMReturn::Error('没有管理该部门的权限', 'PCC009');
            } else {
                $branch_self = Branch::with('branches')->find($branch_id);
                $branch_list = $branch_self->branches;
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现问题，请联系管理员核查', 'PCC008');
        }
        try {
            $resultData = [];
            $start_time = date('Y-m-d H:i:s', $start_time / 1000);
            $end_time = date('Y-m-d H:i:s', $end_time / 1000 - 1);
            foreach ($branch_list as $branch) {
                $is_all = true; // 默认查 所有的 子级部门的业绩。后期修改这里可以查其他的。
                if ($is_all) { // 默认所有
                    $sum_branch_list_id = Utils::getChildSonBranchs($branch->id);
                } else { // 否则只查询本部门
                    $sum_branch_list_id = [$branch->id];
                }
                $branchData = [];
                $branchResultData = $this->branchResult($sum_branch_list_id, $start_time, $end_time, $is_first);
                $branchData[] = $branch->name;
                $branchData[] = $branchResultData['stand'] ?? 0;
                $branchData[] = $branchResultData['size'] ?? 0;
                $resultData[] = $branchData;
            }
            return $resultData;
        } catch (\Throwable $th) {
            return LMReturn::Error('查询出现问题，请联系管理员核查', 'PCC007');
        }
    }

    /**
     * @description: 还本、付息 双 饼状图
     * @param {Request} $request
     * @return {*}
     */
    public function pieDataPrincipalList(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $worker_id = $tokenInfo['worker_id'];
            $worker = Worker::find($worker_id);
            $start_time = $all['start_time'];
            $end_time = $all['end_time'];
            $branch_id = $all['branch_id'] ?? ($worker->branchesManage->first()->id ?? '');
            if ($branch_id == '') { // 则没有权限
                return LMReturn::Error('没有管理该部门的权限', 'PCC002');
            } else {
                $branch_self = Branch::with('branches')->find($branch_id);
                $branch_list = $branch_self->branches;
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现问题，请联系管理员核查', 'PCC001');
        }

        try {
            $resultData = [];
            $start_time = date('Y-m-d H:i:s', $start_time / 1000);
            $end_time = date('Y-m-d H:i:s', $end_time / 1000 - 1);
            foreach ($branch_list as $branch) {
                $is_all = true; // 默认查 所有的 子级部门的业绩。后期修改这里可以查其他的。
                if ($is_all) { // 默认所有
                    $sum_branch_list_id = Utils::getChildSonBranchs($branch->id);
                } else { // 否则只查询本部门
                    $sum_branch_list_id = [$branch->id];
                }
                $branchData = [];
                $branchResultData = $this->branchPrincipal($sum_branch_list_id, $start_time, $end_time);
                $branchData[] = $branch->name;
                $branchData[] = $branchResultData['money'] ?? 0;
                $branchData[] = $branchResultData['interest'] ?? 0;
                $resultData[] = $branchData;
            }
            return $resultData;
        } catch (\Throwable $th) {
            return LMReturn::Error('计算出现问题，请联系管理员核查', 'PCC003');
        }
    }
    /**
     * @description: 入金（Golden） 出金（Withdraw）  双 饼状图  入金=订单金额   出金=出的本+息
     * @param {Request} $request
     * @return {*}
     */
    public function pieDataGoldenWithdrawList(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $worker_id = $tokenInfo['worker_id'];
            $worker = Worker::find($worker_id);
            $start_time = $all['start_time'];
            $end_time = $all['end_time'];
            $branch_id = $all['branch_id'] ?? ($worker->branchesManage->first()->id ?? '');
            if ($branch_id == '') { // 则没有权限
                return LMReturn::Error('没有管理该部门的权限', 'PCC006');
            } else {
                $branch_self = Branch::with('branches')->find($branch_id);
                $branch_list = $branch_self->branches;
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现问题，请联系管理员核查', 'PCC005');
        }

        try {
            $resultData = [];
            $start_time = date('Y-m-d H:i:s', $start_time / 1000);
            $end_time = date('Y-m-d H:i:s', $end_time / 1000 - 1);
            foreach ($branch_list as $branch) {
                $is_all = true; // 默认查 所有的 子级部门的业绩。后期修改这里可以查其他的。
                if ($is_all) { // 默认所有
                    $sum_branch_list_id = Utils::getChildSonBranchs($branch->id);
                } else { // 否则只查询本部门
                    $sum_branch_list_id = [$branch->id];
                }
                $branchData = [];
                $branchResultData = $this->branchPureGolden($sum_branch_list_id, $start_time, $end_time);
                $branchData[] = $branch->name;
                $branchData[] = $branchResultData['course'] ?? 0; // 手续费
                $branchData[] = $branchResultData['cost'] ?? 0; // 运营费
                $branchData[] = $branchResultData['golden'] ?? 0; // 入金
                $branchData[] = $branchResultData['withdraw'] ?? 0; // 出金
                //                $branchData[] = $branchResultData['true_golden'] ?? 0; // 净入金=入金-出金
                //                $branchData[] = $branchResultData['pure_golden'] ?? 0; //实际入金=入金-出金-手续费-运营费
                $resultData[] = $branchData;
            }
            return $resultData;
        } catch (\Throwable $th) {
            return LMReturn::Error('计算出现问题，请联系管理员核查', 'PCC004');
        }
    }
    /**
     * @description: 出金（Withdraw） 双 饼状图  入金=订单金额   出金=出的本+息
     * @param {Request} $request
     * @return {*}
     */
    public function pieDataWithdrawList(Request $request)
    {
    }
    /**
     * @description: 实际入金，净入金 双 饼状图 实际入金=入金-出金-手续费-运营费   净入金=入金-出金
     * @param {Request} $request
     * @return {*}
     */
    public function pieDataPureGoldenList(Request $request)
    {
    }

    /**
     * @description: 手续费，运营费 双 饼状图
     * @param {Request} $request
     * @return {*}
     */
    public function pieDataCostList(Request $request)
    {
    }



    /**
     * @description: 查询部门的年化
     * @param array $branch_list_id 要查询的部门id列表
     * @param {*} $start_time 开始时间
     * @param {*} $end_time 结束时间
     * @param {*} $type 是否为首个订单  1是新单2否存量 3转续，
     * @return {*} 
     */
    public static function branchResult($branch_list_id, $start_time, $end_time, $type = 0)
    {
        $where = [];
        // 开始时间
        $where[] = ["order.sign_time", ">=", $start_time];
        // 结束时间
        $where[] = ["order.sign_time", "<=", $end_time];
        $whereinOrder = [3, 4, 6];
        $sum_data = Order::where($where)
            ->whereIn('order.order_status', $whereinOrder)
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('order.branch_id', $branch_list_id);
            })
            ->when($type > 0, function ($query) use ($type) {
                return $query->where('is_first', $type);
            })
            ->first(
                array(
                    DB::raw('SUM(results_money) as stand'),
                    DB::raw('SUM(order_money) as size')
                )
            )->toArray();
        $sum_data['stand'] = round($sum_data['stand'], 2);
        $sum_data['size'] = round($sum_data['size'], 2);
        return $sum_data; // 年化金额/标准金额
    }
    /**
     * @description: 查询部门的 还本付息
     * @param array $branch_list_id 要查询的部门id列表
     * @param {*} $start_time 开始时间
     * @param {*} $end_time 结束时间
     * @return {*}
     */
    public static function branchPrincipal($branch_list_id, $start_time, $end_time)
    {
        $where = [];
        // 开始时间
        $where[] = ["real_time", ">=", $start_time];
        // 结束时间
        $where[] = ["real_time", "<=", $end_time];
        $sum_data = InterestRecord::where($where)
            ->where('status', '3')
            ->where('is_exit', '2')
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('branch_id', $branch_list_id);
            })
            ->first(
                array(
                    DB::raw('SUM(money) as money'),
                    DB::raw('SUM(interest) as interest')
                )
            )->toArray();
        $sum_data['money'] = round($sum_data['money'], 2);
        $sum_data['interest'] = round($sum_data['interest'], 2);
        return $sum_data;
    }

    /**
     * @description: 查询部门的 出金和入金
     * @param array $branch_list_id 要查询的部门id列表
     * @param {*} $start_time 开始时间
     * @param {*} $end_time 结束时间
     * @return {*}
     */
    public function branchGoldWithdraw($branch_list_id, $start_time, $end_time)
    {
        $where = [];
        // 开始时间
        $where[] = ["real_time", ">=", $start_time];
        // 结束时间
        $where[] = ["real_time", "<=", $end_time];
        // 入金
        $golden = FamiliesMoneyRecord::where($where)
            ->where('type', '1')
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('branch_id', $branch_list_id);
            })
            ->sum('money');
        // 出金
        $withdraw = FamiliesMoneyRecord::where($where)
            ->where('type', '2')
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('branch_id', $branch_list_id);
            })
            ->sum('money');
        $sum_data['golden'] = round($golden, 2); // 入金
        $sum_data['withdraw'] = round(0 - $withdraw, 2); // 出金
        return $sum_data;
    }
    /**
     * @description: 查询部门的 真实入金和净入金
     * @param array $branch_list_id 要查询的部门id列表
     * @param {*} $start_time 开始时间
     * @param {*} $end_time 结束时间
     * @return {*}
     */
    public static function branchPureGolden($branch_list_id, $start_time, $end_time)
    {
        $where = [];
        // 开始时间
        $where[] = ["real_time", ">=", $start_time];
        // 结束时间
        $where[] = ["real_time", "<=", $end_time];
        // 入金
        $golden = FamiliesMoneyRecord::where($where)
            ->where('type', '1')
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('branch_id', $branch_list_id);
            })
            ->sum('money');
        // 出金
        $withdraw = FamiliesMoneyRecord::where($where)
            ->where('type', '2')
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('branch_id', $branch_list_id);
            })
            ->sum('money');
        // 手续费
        $course = FamiliesMoneyRecord::where($where)
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('branch_id', $branch_list_id);
            })
            ->sum('course_money');
        // 运营费
        $cost = FamiliesMoneyRecord::where($where)
            ->where('type', '3')
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('branch_id', $branch_list_id);
            })
            ->sum('money');
        $sum_data['course'] = round($course, 2); // 手续费
        $sum_data['cost'] = round($cost, 2); // 运营费
        $sum_data['golden'] = round($golden, 2); // 入金
        $sum_data['withdraw'] = round(0 - $withdraw, 2); // 出金
        $sum_data['pure_golden'] = $golden + $withdraw; // 净入金=入金-出金
        $sum_data['true_golden'] = $golden + $withdraw - $course - $cost; //实际入金=入金-出金-手续费-运营费
        return $sum_data;
    }
}
